package com.base.web.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.base.web.core.common.HttpClientResult;
import com.base.web.core.enums.WeChatErrorEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * Description: 缓存access_token和jsapi_ticket的单例类(饿汉)
 *
 * @Author: rentie
 * @Date: 2018/5/25 11:15
 **/
public class WeChatUtil {

    private static Logger logger = LoggerFactory.getLogger(WeChatUtil.class);
   private Map<String, String> map = new HashMap<>();

    private WeChatUtil() { }

    private static final WeChatUtil single = new WeChatUtil();

    // 静态工厂方法
   public static WeChatUtil getInstance() {
         return single;
   }

   //获取缓存map，包含access_token和jsApiTicket，系统获取access_token时从这个map里取
   public Map<String, String> getMap(String appid,String appsecret){
       String time = map.get("time");
       String accessToken = map.get("accessToken");
       String jsApiTicket = map.get("jsApiTicket");
       Long nowDate = TimeUtil.getCurrentTimeSecond();

       if (accessToken != null && time != null && jsApiTicket !=null && nowDate - Long.parseLong(time) < 7198) {
           logger.info("accessToken,jsApiTicket存在,且没有超时,返回单例");
       } else {
           //"获取access_token"
           accessToken=getToken(appid,appsecret);

           //"获取jsapi_token";
           jsApiTicket = getJsApiTicket(accessToken);

           map.put("time", nowDate + "");
           map.put("accessToken", accessToken);
           map.put("jsApiTicket", jsApiTicket);
       }

       return map;
   }

    /**
     * 获取公众号access_token
     */
    public static String getToken(String appid,String appsecret){
        String accessToken=null;
        StringBuilder sb = new StringBuilder();
        sb.append("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=");
        sb.append(appid);
        sb.append("&secret=");
        sb.append(appsecret);
        try {
            HttpClientResult result = HttpClientUtils.doGet(sb.toString());
            JSONObject jsonObject = JSON.parseObject(result.getContent());
            if (jsonObject.containsKey("access_token")){
                accessToken = jsonObject.getString("access_token");
                logger.info("获取微信access_token:"+accessToken);
            }else{
                logger.error("获取微信access_token错误信息:"+ WeChatErrorEnum.getMsg(jsonObject.getString("errcode")));
            }

        } catch (Exception e) {
            logger.error("获取微信access_token异常:",e);
        }
        return accessToken;
    }

    /**
     * 获取微信JS接口的临时票据
     * @param accessToken
     * @return
     */
    public static String getJsApiTicket(String accessToken){
        String ticket=null;
        StringBuilder sb = new StringBuilder();
        sb.append("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=");
        sb.append(accessToken);
        sb.append("&type=jsapi");
        try {
            HttpClientResult result = HttpClientUtils.doGet(sb.toString());
            JSONObject jsonObject = JSON.parseObject(result.getContent());
            String errcode=jsonObject.getString("errcode");
            if (Objects.equals("0",errcode)){
                ticket = jsonObject.getString("ticket");
                logger.info("获取jsTicket 票据:"+ticket);
            }else {
                logger.error("获取jsTicket 票据错误信息:"+WeChatErrorEnum.getMsg(errcode));
            }

        } catch (Exception e) {
            logger.error("获取jsTicket 票据异常信息:",e);
        }
        return ticket;
    }
}
